//
//  MainVM.m
//  MyDemo
//
//  Created by jay on 2020/8/22.
//  Copyright © 2020 jay. All rights reserved.
//

#import "MainVM.h"
#import "TXHttpService.h"
#import "HistoryModel.h"
#import "JRDB.h"

@implementation MainVM

- (void)getDataFromNetCompleteHandle:(void(^)(NSError *error))completionHandle {
    
    NSMutableDictionary *dicHeaders = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    NSMutableDictionary *dicParams = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    [[TXHttpService shareInstance] requestWithUrl:kUrlGithubMain headers:dicHeaders params:dicParams method:HttpGet cacheBlock:^(NSDictionary *cacheObj) {
        
        //缓存数据
        if (cacheObj && [cacheObj isKindOfClass:[NSDictionary class]] && cacheObj.count > 0) {

            GithubModel *model = [GithubModel mj_objectWithKeyValues:cacheObj];
            
            self.curModel = model;
            
            completionHandle(nil);
        }
        
    } finishBlock:^(NSDictionary *jsonObj, NSError *error) {

        //网络数据
        if (!error && [jsonObj isKindOfClass:[NSDictionary class]] && jsonObj.count > 0) {
            
            GithubModel *model = [GithubModel mj_objectWithKeyValues:jsonObj];

            self.curModel = model;
            
            //保存历史记录
            HistoryModel *hisModel = [[HistoryModel alloc] init];
            hisModel.timestamp = [[NSDate date] timeIntervalSince1970];
            hisModel.data = [jsonObj mj_JSONString];
            BOOL result = [hisModel jr_save];
            TXLog(@"保存结果：%d", result);
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotifyKeyRecordRefreshed object:nil];
        }
        
        completionHandle(error);
    }];
}

- (NSInteger)rowNumber {
    if (self.curModel) {
        unsigned int count = 0;
        class_copyPropertyList([GithubModel class], &count);
        return count;
    } else {
        return 0;
    }
}

- (NSString *)propertyNameForRow:(NSInteger)row {
    if (self.curModel) {
        unsigned int count = 0;
        objc_property_t *properties = class_copyPropertyList([GithubModel class], &count);
        const char *name = property_getName(properties[row]);
        NSString *propertyName = [NSString stringWithUTF8String:name];
        return propertyName;
    } else {
        return @"";
    }
}

- (NSString *)propertyValueForRow:(NSInteger)row {
    if (self.curModel) {
        unsigned int count = 0;
        objc_property_t *properties = class_copyPropertyList([GithubModel class], &count);
        const char *name = property_getName(properties[row]);
        NSString *propertyName = [NSString stringWithUTF8String:name];
        id propertyValue = [self.curModel valueForKey:propertyName];
        if (propertyValue) {
            return propertyValue;
        } else {
            return @"";
        }
    } else {
        return @"";
    }
}

@end
